package com.vision.web;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpRequestBase;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URI;
import java.util.Enumeration;

/**
 * @Filename HttpConvert.java
 * @Description
 * @Version 1.0
 * @Author zhongc
 * @Email zhong_ch@foxmail.com
 * @History <li>Author: zhongc</li>
 * <li>Date: 2017/3/26</li>
 * <li>Version: 1.0</li>
 * <li>Content: create</li>
 */
public class HttpConvert {

    private static Logger logger = LoggerFactory.getLogger(HttpConvert.class);

    public static HttpRequestBase convertRequest(HttpServletRequest servletRequest, HttpRequestBase httpRequestBase, String url) {
        Enumeration<String> headerNames = servletRequest.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            String headerValue = servletRequest.getHeader(headerName);
            if (headerValue != null) {
                if (headerName.equals("range") && headerValue.equals("bytes=0-1")) {
                    httpRequestBase.setHeader(headerName, "bytes=0-");
                }
                if (headerName.equals("host") || headerName.equals("referer") || headerName.equalsIgnoreCase("if-none-match") || headerName.equalsIgnoreCase("Etag")
                        || headerName.equalsIgnoreCase("x-playback-session-id") || headerName.equalsIgnoreCase("If-Modified-Since")) {
                    continue;
                }
                logger.debug("request header[{}:{}]", headerName, headerValue);
                httpRequestBase.setHeader(headerName, headerValue);
            }
        }
        httpRequestBase.setHeader("accept-encoding", "gzip, deflate");
        httpRequestBase.setHeader("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.79 Safari/537.36 Edge/14.14393");
        httpRequestBase.setHeader("accept", "text/html, application/xhtml+xml, image/jxr, */*");
        httpRequestBase.setURI(URI.create("https://vtt.tumblr.com/" + url));
        servletRequest.getAuthType();
        return httpRequestBase;
    }

    public static InputStream convertResponse(HttpServletResponse servletResponse, CloseableHttpResponse closeableHttpResponse) {
        InputStream content = null;
        try {
            if (closeableHttpResponse.getStatusLine().getStatusCode() == 403) {
                logger.warn("失效资源");
            }
            Header[] allHeaders = closeableHttpResponse.getAllHeaders();
            for (Header header : allHeaders) {
                String headerName = header.getName();
                String headerValue = header.getValue();
                servletResponse.setHeader(headerName, headerValue);
                logger.debug("response header[{}:{}]", headerName, headerValue);
            }
            servletResponse.setHeader("Pragma", "no-cache");
            HttpEntity entity = closeableHttpResponse.getEntity();
            content = entity.getContent();
            int statusCode = closeableHttpResponse.getStatusLine().getStatusCode();
            servletResponse.setStatus(statusCode);
            servletResponse.setContentType(entity.getContentType().getValue());
            servletResponse.setContentLengthLong(entity.getContentLength());
        } catch (Exception e) {
            logger.error("http Convert error:", e);
        }
        return content;

    }
}
